import React from 'react';
import type { JSONTemplateInterface } from '@/components/CustomElement/JSONTemplateForm/interface';
import { ProForm } from '@ant-design/pro-form';
import TemplateFormItem from '@/components/CustomElement/JSONTemplateForm/TemplateFormItem';

// JSON转表单
export const JSONTemplateForm: React.FC<JSONTemplateInterface> = (props) => {
    const { form, layout = 'vertical', template, readonly, disabled, namePrefix, ...rest } = props;
    if (Array.isArray(template)) {
        if (!form) {
            return (
                <>
                    {template?.map((item) => {
                        return (
                            <TemplateFormItem
                                {...item}
                                namePrefix={namePrefix}
                                readonly={readonly || item.readonly}
                                disabled={disabled || item.disabled}
                                itemKey={String(item?.name)}
                                key={item?.key || (item.name as string)}
                            />
                        );
                    })}
                </>
            );
        }
        return (
            <ProForm layout={layout} form={form} {...rest}>
                {template?.map((item) => (
                    <TemplateFormItem
                        {...item}
                        namePrefix={namePrefix}
                        readonly={readonly || item.readonly}
                        disabled={disabled || item.disabled}
                        itemKey={String(item?.name)}
                        key={item?.key || (item.name as string)}
                    />
                ))}
            </ProForm>
        );
    }
    return <div>Invalid form templates, It must be typeof array</div>;
};
